import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:tiktokadult/hj_page/community_business/widget/community_post_widget.dart';
import 'package:tiktokadult/hj_page/community_business/widget/pic_simple_cell_widget.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:tiktokadult/hj_page/mine_business/collec_history_buy/col_his_buy_page.dart';
import 'package:tiktokadult/hj_page/mine_business/collec_history_buy/col_his_buy_sub_page.dart';
import 'package:tiktokadult/hj_page/mine_business/widgets/stage_cell_widget.dart';
import 'package:tiktokadult/hj_utils/api_service/acg_service.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/history_record_util.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

abstract class BaseCBHController extends GetxController {
  final LoadDataType objType;

  BaseCBHController(this.objType);

  bool isLoading = true;
  RefreshController? refreshController;
  final dataSource = [];
  int crossAxisCount = 2;
  double ratio = 1;
  double spaceH = 10;
  EdgeInsets padding = EdgeInsets.only(left: 18.w, right: 18.w, top: 14);
  double spaceV = 14;

  int page = 1;

  @override
  void onInit() {
    super.onInit();
    ratio = objType.ratio;
    crossAxisCount = objType.crossAxisCount;
    spaceH = objType.spaceH;
    spaceV = objType.spaceV;
    padding = objType.padding;
  }

  @override
  void onReady() {
    super.onReady();
    fetchPageData();
  }

  @mustCallSuper
  fetchPageData({bool isRefresh = true}) {
    if (isRefresh) {
      page = 1;
    }
  }

  cancelCollectHandler(int index) => UnimplementedError();

  Widget instanceChildItem(
    int index, {
    bool isEdit = false, //是否在编辑状态
  }) {
    switch (objType) {
      case LoadDataType.game:
        return VideoSimpleCellWidget(
          videoModel: dataSource[index],
          textLines: 1,
        );
      case LoadDataType.video:
        return VideoSimpleCellWidget(videoModel: dataSource[index]);
      case LoadDataType.short:
        final ratio = (dataSource[index] as VideoModel).ratio ?? 0;
        final realRatio = ratio > 0 ? ratio : 1;
        return AspectRatio(
          aspectRatio: realRatio.toDouble(),
          child: VideoSimpleCellWidget(
            videoModel: dataSource[index],
            textLines: 1,
          ),
        );
      case LoadDataType.pictures:
        return PicSimpleCellWidget(
          videoModel: dataSource[index],
          textLines: 1,
        );
      case LoadDataType.post:
        return CommunityPostWidget(videoModel: dataSource[index]);
      case LoadDataType.collections:
        return SimpleCollectionsItem(dataSource[index]);
      case LoadDataType.cartoon:
        return AcgItemWidget(info: dataSource[index]);
      case LoadDataType.comics:
        return AcgItemWidget(info: dataSource[index]);
      case LoadDataType.novel:
        return AcgItemWidget(info: dataSource[index]);
      default:
        throw '';
    }
  }
}

//  collect('我的收藏'),
//   buy('我的购买'),
//   history('历史记录');
//  video(PageStyle.grid),
//   short(PageStyle.grid),
//   comics(PageStyle.grid),
//   cartoon(PageStyle.grid),
//   novel(PageStyle.grid),
//   post(PageStyle.grid),
//   pictures(PageStyle.grid),
//   collections(PageStyle.grid);
BaseCBHController instanceController(PageType pageType, LoadDataType loadType) {
  final type = '${pageType}_$loadType';
  print('BaseCBHController  instanceController   $type');
  switch (type) {
    case 'PageType.like_LoadDataType.video':
    case 'PageType.like_LoadDataType.short':
    case 'PageType.like_LoadDataType.pictures':
    case 'PageType.like_LoadDataType.post':
    case 'PageType.like_LoadDataType.game':
      return LikeVideoController<VideoModel>(loadType);
    case 'PageType.like_LoadDataType.comics':
    case 'PageType.like_LoadDataType.novel':
    case 'PageType.like_LoadDataType.cartoon':
      return LikeVideoController<CartoonMediaInfo>(loadType);
    case 'PageType.collect_LoadDataType.video':
    case 'PageType.collect_LoadDataType.short':
    case 'PageType.collect_LoadDataType.pictures':
    case 'PageType.collect_LoadDataType.post':
    case 'PageType.collect_LoadDataType.game':
      return CollectPageController<VideoModel>(loadType);
    case 'PageType.collect_LoadDataType.comics':
    case 'PageType.collect_LoadDataType.cartoon':
    case 'PageType.collect_LoadDataType.novel':
      return CollectPageController<CartoonMediaInfo>(loadType);
    case 'PageType.collect_LoadDataType.collections':
      return CollectPageController(loadType);
    case 'PageType.buy_LoadDataType.video':
    case 'PageType.buy_LoadDataType.short':
    case 'PageType.buy_LoadDataType.post':
    case 'PageType.buy_LoadDataType.pictures':
    case 'PageType.buy_LoadDataType.game':
      return BuyViodeController<VideoModel>(loadType);
    case 'PageType.buy_LoadDataType.comics':
    case 'PageType.buy_LoadDataType.cartoon':
    case 'PageType.buy_LoadDataType.novel':
      return BuyACGController<CartoonMediaInfo>(loadType);
    case 'PageType.buy_LoadDataType.collections':
      return BuyCollectionsController(loadType);
    case 'PageType.history_LoadDataType.video':
    case 'PageType.history_LoadDataType.short':
    case 'PageType.history_LoadDataType.post':
    case 'PageType.history_LoadDataType.pictures':
    case 'PageType.history_LoadDataType.game':
      return HistoryController<VideoModel>(loadType);
    case 'PageType.history_LoadDataType.comics':
    case 'PageType.history_LoadDataType.novel':
    case 'PageType.history_LoadDataType.cartoon':
      return HistoryController<CartoonMediaInfo>(loadType);
    case 'PageType.history_LoadDataType.collections':
  }
  throw '$type 没有定义';
}

class HistoryController<T> extends BaseCBHController {
  HistoryController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    super.fetchPageData(isRefresh: isRefresh);
    final historys = await HistoryRecordUtil.fetchHistory<T>(objType.historyType);

    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
    }
    dataSource.addAll(historys);
    refreshController?.refreshCompleted();
    refreshController?.loadNoData();

    update();
  }

  @override
  cancelCollectHandler(int index) async {
    final model = dataSource[index];
    if (model is VideoModel) {
      await HistoryRecordUtil.deleteHistoryModel<VideoModel>(model, objType.historyType);
      dataSource.remove(model);
      update();
    } else if (model is CartoonMediaInfo) {
      await HistoryRecordUtil.deleteHistoryModel<CartoonMediaInfo>(model, objType.historyType);
      dataSource.remove(model);
      update();
    } else {
      debugLog("删除类型未处理");
    }
  }
}

class BuyCollectionsController<T> extends BaseCBHController {
  BuyCollectionsController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    // super.fetchPageData(isRefresh: isRefresh);
    // final res = await MineService.fetchMineBuyCollections(2, page: page);
    // isLoading = false;
    // if (isRefresh) {
    //   dataSource.clear();
    //   refreshController?.refreshCompleted();
    // }
    // if (res?.hasNext ?? false) {
    //   refreshController?.loadComplete();
    // } else {
    //   refreshController?.loadNoData();
    // }
    // dataSource.addAll(res?.list ?? []);
    // page += 1;
    // update();
  }
}

class BuyACGController<T> extends BaseCBHController {
  BuyACGController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    super.fetchPageData(isRefresh: isRefresh);
    final res = await ACGService.fetchAcgBuyData<T>(page, 12, mediaType: objType.buyType);
    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
      refreshController?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
    dataSource.addAll(res?.list ?? []);
    page += 1;
    update();
  }
}

class BuyViodeController<T> extends BaseCBHController {
  BuyViodeController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    super.fetchPageData(isRefresh: isRefresh);

    final res = await MineService.fetchMineBuyVideo(newsType: objType.buyType, page: page, size: 12);
    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
      refreshController?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
    dataSource.addAll(res?.list ?? []);
    page += 1;
    update();
  }
}

class LikeVideoController<T> extends BaseCBHController {
  LikeVideoController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    super.fetchPageData(isRefresh: isRefresh);

    final res = await MineService.fetchMyLike(likeType: objType.buyType, page: page, size: 12);
    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
      refreshController?.refreshCompleted();
    }
    if (res.hasNext ?? false) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
    dataSource.addAll(res.list ?? []);
    page += 1;
    update();
  }
}

class CollectPageController<T> extends BaseCBHController {
  CollectPageController(super.objType);

  @override
  fetchPageData({bool isRefresh = true}) async {
    super.fetchPageData(isRefresh: isRefresh);
    try {
      dynamic res;
      if (objType == LoadDataType.cartoon || objType == LoadDataType.comics || objType == LoadDataType.novel) {
        res = await ACGService.fetchAcgBooklib<T>(objType.collectType, page: page, size: 12);
      } else {
        res = await MineService.fetchMineCollectList<T>(objType.collectType, page: page, size: 12);
      }
      isLoading = false;
      if (isRefresh) {
        dataSource.clear();
        refreshController?.refreshCompleted();
      }
      if (res?.hasNext ?? false) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
      dataSource.addAll(res?.list ?? []);
      page += 1;
    } catch (e) {
      refreshController?.refreshCompleted();
      refreshController?.loadComplete();
      debugLog(e);
    }
    update();
  }

  @override
  cancelCollectHandler(int index) async {
    final model = dataSource[index];
    if (model is VideoModel) {
      final result = await MineService.postCollect(model.id, objType.collectType, false);
      if (result) {
        dataSource.remove(model);
        update();
      }
    } else if (model is CartoonMediaInfo) {
      final result = await ACGService.mediaBookshelfDelete(model.id ?? "");
      if (result) {
        dataSource.remove(model);
        update();
      }
    } else {
      debugLog("删除类型未处理");
    }
  }
}
